package com.glowdayz.glowmee;

import java.io.IOException;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PorterDuff;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;

import com.glowdayz.common.ActivityManager;
import com.glowdayz.common.CDialog;
import com.glowdayz.common.XmlParser;
import com.glowdayz.model.AddItem;
import com.glowdayz.model.UserInfo;
import com.google.android.gcm.GCMRegistrar;

public class MainActivity extends Activity implements OnClickListener {
	
	private ActivityManager am = ActivityManager.getInstance();

	ImageView joinBtn = null, arroundBtn = null, loginBtn = null;
	String url = null, mail = null, nickName = null;
	
	String regId = "";
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        
        am.addActivity(this);
        
        registerGcm();
        
		Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				SharedPreferences prefs = getSharedPreferences("Save", MODE_PRIVATE);
				if (prefs.getBoolean("auto", true) && prefs.getString("eMail", "") != null && !prefs.getString("eMail", "").equals("") && 
						prefs.getString("pw", "") != null && !prefs.getString("pw", "").equals("")) {
					url = getResources().getString(R.string.server_url) + "/glowmee/loginRegisterXml.do?";
					url += "eMail=" + prefs.getString("eMail", "") + "&password=" + prefs.getString("pw", "") + "&regId=" + regId;
					(new LoginWorker()).execute();
				} else {
					setContentView(R.layout.activity_main);
					joinBtn = (ImageView) findViewById(R.id.joinBtn);
			        joinBtn.setOnTouchListener(new OnTouchListener() {
			            @Override
			            public boolean onTouch(View v, MotionEvent event) {
			                switch (event.getAction()) {
			                    case MotionEvent.ACTION_DOWN: {
			                        ImageView view = (ImageView) v;
			                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
			                        view.invalidate();
			                        break;
			                    }
			                    case MotionEvent.ACTION_UP:
			                    case MotionEvent.ACTION_CANCEL: {
			                        ImageView view = (ImageView) v;
			                        view.getDrawable().clearColorFilter();
			                        view.invalidate();
			                        break;
			                    }
			                }
			                return false;
			            }
			        });
			        joinBtn.setOnClickListener(MainActivity.this);
			        
			        arroundBtn = (ImageView) findViewById(R.id.arroundBtn);
			        arroundBtn.setOnTouchListener(new OnTouchListener() {
			            @Override
			            public boolean onTouch(View v, MotionEvent event) {
			                switch (event.getAction()) {
			                    case MotionEvent.ACTION_DOWN: {
			                        ImageView view = (ImageView) v;
			                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
			                        view.invalidate();
			                        break;
			                    }
			                    case MotionEvent.ACTION_UP:
			                    case MotionEvent.ACTION_CANCEL: {
			                        ImageView view = (ImageView) v;
			                        view.getDrawable().clearColorFilter();
			                        view.invalidate();
			                        break;
			                    }
			                }
			                return false;
			            }
			        });
			        arroundBtn.setOnClickListener(MainActivity.this);
			        
			        loginBtn = (ImageView) findViewById(R.id.loginBtn);
			        loginBtn.setOnTouchListener(new OnTouchListener() {
			            @Override
			            public boolean onTouch(View v, MotionEvent event) {
			                switch (event.getAction()) {
			                    case MotionEvent.ACTION_DOWN: {
			                        ImageView view = (ImageView) v;
			                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
			                        view.invalidate();
			                        break;
			                    }
			                    case MotionEvent.ACTION_UP:
			                    case MotionEvent.ACTION_CANCEL: {
			                        ImageView view = (ImageView) v;
			                        view.getDrawable().clearColorFilter();
			                        view.invalidate();
			                        break;
			                    }
			                }
			                return false;
			            }
			        });
			        loginBtn.setOnClickListener(MainActivity.this);
				}
			}
		};
		// 스플래시 이미지 3초동안 표시
		handler.sendEmptyMessageDelayed(0, 2000);
        
    }
    
    public class LoginWorker extends AsyncTask<Object, AddItem, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(MainActivity.this);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			// XML 파서 생성
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			// 통신 실패시 예외처리
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				/** 읽은 내용을 담기 위한 변수 */
				String rt = null;
				String rtmsg = null;
				int seq = 0;
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("rt")) {
							parser.next();
							rt = parser.getText();
						} else if (tag.equals("rtmsg")) {
							parser.next();
							rtmsg = parser.getText();
						} else if (tag.equals("seq")) {
							parser.next();
							seq = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("mail")) {
							parser.next();
							mail = parser.getText();
						} else if (tag.equals("nickName")) {
							parser.next();
							nickName = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("JSPglowmee")) {
							AddItem item = new AddItem(rt, rtmsg, seq);
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(AddItem... param) {
			
			if (param[0].getRt().equals("SUCCESS")) {
				UserInfo.getInstance().setUSER_ID(param[0].getSeq());
				UserInfo.getInstance().setUSER_EMAIL(mail.trim());
				UserInfo.getInstance().setUSER_NICKNAME(nickName.trim());
				UserInfo.getInstance().setAUTO_LOGIN(true);
				
				Intent intent = new Intent(MainActivity.this, Index.class);
				startActivity(intent);
			} else {
				AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, android.R.style.Theme_Holo_Light_Dialog));
				alert.setTitle("로그인 실패");
				alert.setMessage(param[0].getRtmsg());
				alert.setCancelable(false);
				alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(MainActivity.this, Login.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
						startActivity(intent);
					}
				});
				alert.create();
				alert.show();
			}
			
		}

		@Override
		protected void onPostExecute(Object param) {
			CDialog.hideLoading();
		}
		
		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new LoginWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
    
    @Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.joinBtn:
			Intent joinFirst = new Intent(this, JoinFirst.class);
			joinFirst.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
			startActivity(joinFirst);
			break;
		case R.id.loginBtn:
			Intent login = new Intent(this, Login.class);
			login.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
			startActivity(login);
			break;
		case R.id.arroundBtn:
			Intent index = new Intent(this, Index.class);
			startActivity(index);
			break;
		}
	}
    
    public void registerGcm() {

		GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);

		regId = GCMRegistrar.getRegistrationId(this);

		if ("".equals(regId)) {
			GCMRegistrar.register(this, "883691140050");
		} else {
			Log.e("id", "regId : " + regId);
		}
	}
    
    @Override
	protected void onDestroy() {
		super.onDestroy();
		am.removeActivity(this);
	}

}
